package com.samehope.ar.socket.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 用于检测channel心跳的handler
 * @Author: ZhangLuo
 * @Email: 1946430@qq.com
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        System.out.println(evt.getClass());

        if (evt instanceof IdleStateEvent) {
            // 判断evt是否是IdleStateEvent(用于触发用户事件, 包含 读空闲 / 写空闲 / 读写空闲)

            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state() == IdleState.READER_IDLE) {
                log.info("进入读空闲...");
            } else if (event.state() == IdleState.WRITER_IDLE) {
                log.info("进入写空闲...");
            } else if (event.state() == IdleState.ALL_IDLE) {
                log.info("channel 关闭前, user的数量为: {}", AppClientHandler.users.size());

                Channel channel = ctx.channel();
                // 关闭无用的channel, 防止资源浪费
                channel.close();
                log.info("channel 关闭后, user的数量为: {}", AppClientHandler.users.size());
            }
        }
    }
}
